package com.tu.tropicana.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.DataSources;
import com.tu.tropicana.dao.DataSourceManager;

public class C3p0DataSourceManager implements DataSourceManager{

	private static final Logger LOGGER = 
		Logger.getLogger( C3p0DataSourceManager.class );
	
	private final static String PROPERTIES_PATH = "jdbc";
	
	private static final DataSourceManager MANAGER = new C3p0DataSourceManager();
	
	private String driverName;
	
	private String username;
	
	private String password;
	
	private String url;
	
	private Map properties;
	
	private DataSource pooledDataSource;
	
	public static DataSourceManager getInstance(){
		
		return MANAGER;
	}
	
	private C3p0DataSourceManager(){
		
		this.setConnectionString();
		
		try {
			
			Class.forName( driverName );
			DataSource unpooledDataSource = DataSources.unpooledDataSource( url, 
					username, password );
			
			properties = new HashMap();
			properties.put( "maxPoolSize", new Integer( 60 ) );
			properties.put( "minPoolSize", new Integer( 5 ) );
			
			pooledDataSource = DataSources.pooledDataSource( unpooledDataSource, properties );
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public Connection getConnection() throws SQLException {

		return pooledDataSource.getConnection();
	}

	public void setDriverName(String driverName) {
		this.driverName = driverName;
		
	}

	public void setPassword(String password) {
		this.password = password;
		
	}

	public void setUrl(String url) {
		this.url = url;
		
	}

	public void setUsername(String username) {
		this.username = username;
		
	}

	private void setConnectionString(){
		
		LOGGER.debug( "setConnectionString start" );
		
		ResourceBundle resource = ResourceBundle.getBundle( PROPERTIES_PATH );
		this.setDriverName( resource.getString( "driverClassName" ) );
		this.setUrl( resource.getString( "url" ) );
		this.setUsername( resource.getString( "username" ) );
		this.setPassword( resource.getString( "password") );
		
		LOGGER.debug( "setConnectionString end" );
	}
}
